// 解构出的函数
//   createRouter           -  用于创建路由的函数
//   createWebHashHistory   -  哈希路由模式
//   createWebHistory       -  History 模式
import { createRouter, createWebHashHistory } from 'vue-router'

import Layout from '@/views/Layout.vue'
import Home from '@/views/home/index.vue'
import store from '@/store'
import { h } from 'vue-demi'

const Login = () => import('@/views/login/index.vue')
const TopCategory = () => import('@/views/category/index.vue')
const SubCategory = () => import('@/views/category/sub.vue')
const Goods = () => import('@/views/goods/index.vue')
const Callback = () => import('@/views/login/callback.vue')
const Cart = () => import('@/views/cart/index.vue')
const PayCheckout = () => import('@/views/member/pay/checkout.vue')
const PayIndex = () => import('@/views/member/pay/index.vue')
const PayCallback = () => import('@/views/member/pay/callback.vue')
const MemberLayout = () => import('@/views/member/Layout.vue')
const MemberHome = () => import('@/views/member/home/index.vue')
const MemberOrder = () => import('@/views/member/order/index.vue')
const MemberOrderDetail = () => import('@/views/member/order/detail.vue')

// 路由配置 - 路径和组件的映射关系
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: Home },
      { path: 'category/:id', component: TopCategory },
      { path: 'category/sub/:id', component: SubCategory },
      { path: 'product/:id', component: Goods },
      { path: 'cart', component: Cart },
      { path: 'member/checkout', component: PayCheckout },
      { path: 'member/pay', component: PayIndex },
      { path: 'pay/callback', component: PayCallback },
      {
        path: '/member',
        component: MemberLayout,
        children: [
          { path: '/member', component: MemberHome },
          {
            path: '/member/order',
            component: { render: () => h(<RouterView />) },
            children: [
              { path: '', component: MemberOrder },
              { path: ':id', component: MemberOrderDetail }
            ]
          }
        ]
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/login/callback',
    component: Callback
  }
]

// 创建路由实例
const router = createRouter({
  // 使用哈希路由模式
  history: createWebHashHistory(),
  // 路由配置
  routes,
  // 滚动行为
  scrollBehavior (to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 }
  }
})
// console.log(router.currentRoute)

router.beforeEach((to, from, next) => {
  const token = store.state.user.profile.token
  // console.log(token)
  if (!token && to.path.startsWith('/member')) {
    console.log(111)
    next(`/login?redirectUrl=${to.fullPath}`)
  }
  // 普通情况，直接放行
  next()
})

export default router
